import 'dart:convert';
import 'dart:io';
import 'package:device_info/device_info.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
import 'forgot_password.dart';
import 'register.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:keyboard_avoider/keyboard_avoider.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class Login extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return LoginForm();
  }
}

class LoginForm extends StatefulWidget {
  @override
  LoginFormState createState() => LoginFormState();
}

class LoginFormState extends State<LoginForm> {
  DateTime _lastTime;
  final loginFormKey = GlobalKey<FormState>();
  String username, password;
  bool autovalidate = false;
  String uniqueId = '';

  @override
  void initState() {
    super.initState();
    this.getDeviceId();
    this._validateLogin();
  }

  Future _validateLogin() async {
    Future future = Future(() async {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      return prefs.getString("username");
    });
    future.then((val) {
      if (val == null) {
        setState(() {
          username = '';
        });
      } else {
        setState(() {
          username = val;
        });
      }
    }).catchError((_) {
      print("catchError");
    });
  }

  void getDeviceId() async {
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    print(Platform);
    if (Platform.isIOS) {
      IosDeviceInfo iosDeviceInfo = await deviceInfo.iosInfo;
      uniqueId = iosDeviceInfo.identifierForVendor;
    } else {
      AndroidDeviceInfo androidDeviceInfo = await deviceInfo.androidInfo;
      uniqueId = androidDeviceInfo.androidId;
    }
  }

  void submitLoginForm() {
    if (loginFormKey.currentState.validate()) {
      loginFormKey.currentState.save();
      this.fetchPosts(username, password);
      // debugPrint('username: $username');
      // debugPrint('password: $password');
      EasyLoading.show(
          status: 'loading...', maskType: EasyLoadingMaskType.black);
    } else {
      setState(() {
        autovalidate = true;
      });
    }
  }

  String validateUsername(value) {
    if (value.isEmpty) {
      return '用户名不能为空！';
    }

    return null;
  }

  String validatePassword(value) {
    if (value.isEmpty) {
      return '密码不能为空！';
    }

    return null;
  }

  @override
  Widget build(BuildContext context) {
    if (username != null) {
      return WillPopScope(
          child: Scaffold(
            resizeToAvoidBottomInset: false,
            appBar: AppBar(
              automaticallyImplyLeading: false, // 去除返回按钮
              title: Text('登录'),
              centerTitle: true,
              elevation: 0.0,
            ),
            body: Theme(
              data: Theme.of(context).copyWith(
                primaryColor: Colors.black,
              ),
              child: Container(
                padding: EdgeInsets.all(16.0),
                child: KeyboardAvoider(
                    autoScroll: true,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Form(
                          key: loginFormKey,
                          child: Column(
                            children: <Widget>[
                              TextFormField(
                                initialValue: username,
                                decoration: InputDecoration(
                                  labelText: '用户名',
                                  helperText: '',
                                ),
                                onSaved: (value) {
                                  username = value;
                                },
                                validator: validateUsername,
                                // autovalidate: autovalidate,
                              ),
                              TextFormField(
                                obscureText: true,
                                decoration: InputDecoration(
                                  labelText: '密码',
                                  helperText: '',
                                ),
                                onSaved: (value) {
                                  password = value;
                                },
                                validator: validatePassword,
                                // autovalidate: autovalidate,
                              ),
                              SizedBox(
                                height: 32.0,
                              ),
                              Container(
                                width: double.infinity,
                                child: ElevatedButton(
                                  // color: Theme.of(context).accentColor,
                                  child: Text('登录',
                                      style: TextStyle(color: Colors.white)),
                                  onPressed: submitLoginForm,
                                ),
                              ),
                              SizedBox(
                                height: 32.0,
                              ),
                              Container(
                                  width: double.infinity,
                                  child: Row(
                                    children: <Widget>[
                                      Text('忘记密码，现在去'),
                                      TextButton(
                                        style: ButtonStyle(
                                            // foregroundColor: Theme.of(context).accentColor, //字体颜色
                                            elevation:
                                                MaterialStateProperty.all(0)),
                                        child: Text('找回',
                                            style: TextStyle(
                                                fontSize: 20,
                                                fontWeight: FontWeight.w500)),
                                        onPressed: () {
                                          Navigator.of(context).push(
                                              MaterialPageRoute(
                                                  builder: (context) =>
                                                      ForgotPassword(
                                                          uniqueId: uniqueId)));
                                        },
                                      ),
                                    ],
                                  )),
                              SizedBox(
                                height: 10.0,
                              ),
                              Container(
                                  width: double.infinity,
                                  child: Row(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: <Widget>[
                                      Text('我还没有账号，现在去'),
                                      TextButton(
                                        style: ButtonStyle(
                                            // foregroundColor: Theme.of(context).accentColor, //字体颜色
                                            elevation:
                                                MaterialStateProperty.all(0)),
                                        child: Text('注册',
                                            style: TextStyle(
                                                fontSize: 20,
                                                fontWeight: FontWeight.w500)),
                                        onPressed: () {
                                          // Navigator.of(context).pushNamed('/register');
                                          Navigator.of(context).push(
                                              MaterialPageRoute(
                                                  builder: (context) =>
                                                      Register(
                                                          uniqueId: uniqueId)));
                                        },
                                      ),
                                    ],
                                  )),
                            ],
                          ),
                        )
                      ],
                    )),
              ),
            ),
          ),
          onWillPop: () async {
            if (_lastTime == null ||
                DateTime.now().difference(_lastTime) > Duration(seconds: 1)) {
              //两次点击间隔超过1s重新计时
              _lastTime = DateTime.now();
              Fluttertoast.showToast(
                  msg: '再按一次退出应用',
                  toastLength: Toast.LENGTH_SHORT,
                  gravity: ToastGravity.CENTER,
                  timeInSecForIosWeb: 1,
                  backgroundColor: Colors.white,
                  textColor: Colors.black87,
                  fontSize: 16.0);
              return false;
            }
            return true;
          });
    } else {
      return Form(key: loginFormKey, child: Column());
    }
  }

  Future fetchPosts($username, $password) async {
    var dataBody = jsonEncode({'username': $username, 'password': $password});
    final response = await http.post('https://me.yuanqiao.pw/api/me/login.php',
        body: dataBody);
    EasyLoading.dismiss();
    if (response.statusCode == 200) {
      final responseBody = json.decode(response.body);
      print('responseBody');
      print(responseBody);
      var state = responseBody['state'];
      if (state == '1') {
        String token = responseBody['data']['token'];
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setString('nickname', responseBody['data']['nickname']);
        prefs.setString('username', responseBody['data']['username']);
        prefs.setString(
            'email',
            responseBody['data']['email'] != null
                ? responseBody['data']['email']
                : '');
        final setTokenResult = await prefs.setString('user_token', token);
        if (setTokenResult) {
          Fluttertoast.showToast(
              msg: responseBody['error'],
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.CENTER,
              timeInSecForIosWeb: 1,
              backgroundColor: Colors.white,
              textColor: Colors.black87,
              fontSize: 16.0);
          debugPrint('保存登录token成功');
          Navigator.of(context).pushNamedAndRemoveUntil(
            '/home',
            (route) => route == null,
          );
          // Navigator.of(context).pushAndRemoveUntil(
          //     new MaterialPageRoute(builder: (context) => Home()),
          //     (route) => route == null);
        } else {
          Fluttertoast.showToast(
              msg: '保存登录token失败',
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.CENTER,
              timeInSecForIosWeb: 1,
              backgroundColor: Colors.white,
              textColor: Colors.black87,
              fontSize: 16.0);
        }
      } else {
        Fluttertoast.showToast(
            msg: responseBody['error'],
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 1,
            backgroundColor: Colors.white,
            textColor: Colors.black87,
            fontSize: 16.0);
      }
    } else {
      Fluttertoast.showToast(
          msg: '网络或服务器错误',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.white,
          textColor: Colors.black87,
          fontSize: 16.0);
    }
  }
}
